import { logger } from '@/config/logger';
import express from 'express';
import { UnauthorizedError } from 'express-jwt';
import { Result, ValidationError } from 'express-validator';

const validationErrorType = ['field', 'alternative', 'alternative_grouped', 'unknown_fields']

export class HttpError<T> extends Error {
    protected readonly code?: number
    protected readonly msg?: string
    protected readonly data?: T

    constructor(params?: { code?: number, msg?: string, data?: T }) {
        const { code, msg, data } = params || {};
        super(msg)
        this.code = code
        this.msg = msg
        this.data = data
    }
}

type ResultError = UnauthorizedError | Result | Error
export const gloabErrorHandler = (err: ResultError, req: express.Request, res: express.Response, next: express.NextFunction) => {
    if (err instanceof UnauthorizedError) {
        res.status(401).send()
        req.log.error({ req, res, err: err.message }, "request errored")
        return
    }

    if (err instanceof Result) {
        res.status(400).json(err.array())
        req.log.error({ req, res, err }, "request errored")
        return
    }

    if (err instanceof HttpError) {
        res.status(500).json(err)
        req.log.error({ req, res, err: err.message }, "request errored")
        return
    }

    next(err)
}